<template>
  <div class="order">
    <el-card class="box-card">
      <div>
        <el-form :model="queryParam" ref="queryParam" inline>
          <el-form-item label="订单ID:" label-width="100px" prop="id">
            <el-input v-model="queryParam.id" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="订单编号:" label-width="100px" prop="orderNo">
            <el-input v-model="queryParam.orderNo" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="客户ID:" label-width="100px" prop="customerId">
            <el-input v-model="queryParam.customerId" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="客户名字:" label-width="100px" prop="customerName">
            <el-input v-model="queryParam.customerName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="客户电话:" label-width="100px" prop="tel">
            <el-input v-model="queryParam.tel" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="物流单号:" label-width="100px" prop="trankNo">
            <el-input v-model="queryParam.trankNo" autocomplete="off"></el-input>
          </el-form-item>
          <!-- </el-form>
          <el-form :model="queryParam" ref="queryParam" inline>-->
          <el-form-item label="订单来源:" label-width="100px" prop="sourceType">
            <el-select
              v-model="queryParam.sourceType"
              placeholder="请选择订单来源"
              clearable
              @change="changeType"
            >
              <el-option
                v-for="item in fromList"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="来源:" label-width="100px" prop="sourceId" v-if="sourceIdVisable">
            <el-select
              v-model="queryParam.sourceId"
              placeholder="请输入关键词"
              clearable
              filterable
              remote
              :remote-method="remoteMethod"
              :loading="loading"
            >
              <el-option
                v-for="item in sourceIdList"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态:" label-width="100px" prop="status">
            <el-select v-model="queryParam.status" placeholder="请选择状态" clearable>
              <el-option
                v-for="item in statusList"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围:" label-width="100px" prop="timespan">
            <el-date-picker
              v-model="queryParam.timespan"
              type="daterange"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getList()">搜索</el-button>
            <el-button @click="resetForm('queryParam')">重置</el-button>
            <el-button @click="exportExcel()">导出</el-button>
            <el-button @click="dialogOrderProperties()">订单配置</el-button>
          </el-form-item>
          <el-form-item label="总金额:" label-width="100px">{{sumOrderAmount}}</el-form-item>
        </el-form>
      </div>
      <div class="boxcard-body">
        <div class="tableList">
          <el-table
            :data="list"
            border
            style="width: 100%"
            :header-cell-style="{ 'background-color': '#EEEEEE' }"
          >
            <el-table-column type="index" label="排序" width="50"></el-table-column>
            <el-table-column prop="orderNo" label="订单编号" width="150" show-overflow-tooltip></el-table-column>
            <el-table-column prop="customerName" label="客户名字" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="tel" label="客户手机" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="customerMessage" label="客户留言" width="150" show-overflow-tooltip></el-table-column>
            <el-table-column label="状态" width="100" show-overflow-tooltip>
              <template slot-scope="scope">{{ getStatus(scope.row.status) }}</template>
            </el-table-column>
            <el-table-column prop="paidDate" label="支付日期" width="150" show-overflow-tooltip></el-table-column>
            <el-table-column prop="amount" label="订单总额" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="realAmount" label="实际支付额" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="agentOffAmount" label="代理卡抵扣金额" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="creditsOffAmount" label="积分抵消额" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="couponOffAmount" label="优惠券抵消额" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="carrier" label="发货物流商" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="trankNo" label="物流单号" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="shipper" label="发货人" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column prop="shipTime" label="发货时间" width="150" show-overflow-tooltip></el-table-column>
            <el-table-column prop="sourceType" label="客户来源" width="100" show-overflow-tooltip>
              <template slot-scope="scope">{{ getSourceType(scope.row.sourceType) }}</template>
            </el-table-column>
            <el-table-column prop="recommender" label="推荐人" width="100" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" fixed="right" width="180">
              <template slot-scope="scope">
                <el-button @click="dialogField(scope.row)" type="text" round size="small">详情</el-button>
                <el-button
                  v-if="(scope.row.status == 2 ||scope.row.status == 10) && !scope.row.isApplyAllRefund"
                  @click="sendDialog(scope.row)"
                  type="text"
                  size="small"
                >发货</el-button>
                <el-button
                  v-if="scope.row.status == 2 && !scope.row.isApplyAllRefund"
                  @click="sending(scope.row)"
                  type="text"
                  size="small"
                >发货中</el-button>
                <el-button
                  v-if="scope.row.isApplyAllRefund"
                  @click="allRefundDialog(scope.row)"
                  type="text"
                  size="small"
                >全额退款申请</el-button>
                <el-button
                  v-if="scope.row.status == 3||scope.row.status == 4||scope.row.status == 5||scope.row.status == 6 "
                  @click="lookLogistics(scope.row)"
                  type="text"
                  size="small"
                >查看物流</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="pageChange"
              :total="total"
              :current-page.sync="pageNum"
              :page-sizes="[10, 20]"
              :page-size="10"
              layout="total, sizes, prev, pager, next"
            ></el-pagination>
          </div>
        </div>
      </div>
    </el-card>
    <!-- 详情弹窗 -->
    <div>
      <orderDetail v-bind:id="id" v-bind:visible.sync="dialogFieldBox"></orderDetail>
    </div>
    <courier v-bind:visible.sync="courierDialog" ref="courier"></courier>
    <!-- 发货弹窗 -->
    <div>
      <el-dialog title="发货" :visible.sync="sendVisible">
        <el-form :model="send" ref="send">
          <el-form-item label="发货物流商：" label-width="120px" prop="carrier">
            <el-select v-model="send.carrier" placeholder="发货物流商" clearable>
              <el-option
                v-for="item in kuaidiList"
                :key="item.key"
                :label="item.label"
                :value="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物流号：" label-width="120px" prop="trankNo">
            <el-input v-model="send.trankNo" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="发货人：" label-width="120px" prop="shipper">
            <el-input v-model="send.shipper" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="sendCancel()">取 消</el-button>
          <el-button type="primary" @click="sendSubmit()">提 交</el-button>
        </div>
      </el-dialog>
    </div>
    <a :href="downExcelUrl" id="downExcel" target="_blank" style="display:none;"></a>
    <orderProperties ref="orderProperties" v-bind:visible.sync="orderPropertiesDialog"></orderProperties>
  </div>
</template>

<script>
import orderDetail from "@/views/order/orderDetail";
import courier from "@/views/order/courier";
import orderProperties from "@/views/order/orderProperties";

export default {
  components: { orderDetail, courier,orderProperties },
  data() {
    return {
      // 分页参数
      pageNum: 1, // 当前页数
      pageSize: 10, // 页大小
      total: 0, // 数据总条数
      list: [], // 数据列表
      queryParam: {
        id: null,
        orderNo: null,
        customerId: null,
        status: null,
        timespan: null,
        sourceType: null,
        sourceId: null,
        trankNo: null,
        customerName: null,
        tel: null
      },
      // 弹窗相关属性
      dialogFieldBox: false,
      courierDialog: false,
      id: "",
      statusList: [],
      kuaidiList: [],
      sendVisible: false,
      send: {
        id: "",
        carrier: "",
        trankNo: "",
        shipper: ""
      },
      fromlabel: "所有来源",
      fromList: [
        { key: 1, label: "医生宣传" },
        { key: 2, label: "代理宣传" },
        { key: 3, label: "客户" },
        { key: 4, label: "门店" },
        { key: 5, label: "筛查活动" },
        { key: 6, label: "其他" }
      ],
      orderTime: "近一个月",
      timeList: [
        { key: 1, label: "所有时间" },
        { key: 2, label: "近一个月" },
        { key: 3, label: "近三个月" }
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            }
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            }
          }
        ]
      },
      dates: "",
      downExcelUrl: "",
      sumOrderAmount: 0,
      sourceIdList: [],
      sourceIdVisable: false,
      sourceIdRemoteUrl: "",
      loading: false,
      orderPropertiesDialog:false
    };
  },
  created() {
    this.ininDict();
    if (this.$route.query.customerId) {
      this.queryParam.customerId = this.$route.query.customerId;
    }
    this.getList();
  },
  activated() {
    if (this.$route.query.customerId) {
      this.queryParam.customerId = this.$route.query.customerId;
      this.getList();
    }
  },
  computed: {},
  watch: {},
  methods: {
    async ininDict() {
      await this.$https.get("order/orderStatus").then(res => {
        this.statusList = res.data.data;
      });
      await this.$https.get("order/kuaidi").then(res => {
        this.kuaidiList = res.data.data;
      });
    },
    getStatus(status) {
      for (let i = 0; i < this.statusList.length; i++) {
        if (this.statusList[i].key == status) {
          return this.statusList[i].label;
        }
      }
      return "";
    },
    getSourceType(status) {
      for (let i = 0; i < this.fromList.length; i++) {
        if (this.fromList[i].key == status) {
          return this.fromList[i].label;
        }
      }
      return "其他";
    },
    // 分页相关方法
    // 页大小改变时
    handleSizeChange(val) {
      this.pageSize = val;
    },
    // 页码改变时
    pageChange(e) {
      // 获取某页数据
      this.pageNum = e;
      this.getList();
    },
    // 获取列表数据
    getList() {
      let date1 = null,
        date2 = null;
      if (
        this.queryParam.timespan != null &&
        this.queryParam.timespan.length > 1
      ) {
        date1 = this.queryParam.timespan[0];
        date2 = this.queryParam.timespan[1];
      }
      let param = {
        id: this.queryParam.id,
        orderNo: this.queryParam.orderNo,
        customerId: this.queryParam.customerId,
        status: this.queryParam.status,
        startDate: date1,
        endDate: date2,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        sourceType: this.queryParam.sourceType,
        trankNo: this.queryParam.trankNo,
        customerName: this.queryParam.customerName,
        tel: this.queryParam.tel,
        sourceId: this.queryParam.sourceId
      };
      this.$https.get("/order/pageOrder", param).then(res => {
        this.list = res.data.data.list;
        this.total = Number.parseInt(res.data.data.total);
        this.pageNum = res.data.data.pageNum;
      });
      this.$https.get("/order/sumOrderAmount", param).then(res => {
        this.sumOrderAmount = res.data.data;
      });
    },
    // 编辑按钮打开编辑字段弹窗
    dialogField(e) {
      this.dialogFieldBox = true;
      this.id = e.id;
    },
    sending(row) {
      this.$confirm("确定发货中?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$https
            .postXform("order/orderSending", { id: row.id })
            .then(res => {
              this.$message({ message: "发货中成功", type: "success" });
              row.status = 10;
            });
        })
        .catch(() => {});
    },
    sendDialog(row) {
      this.sendVisible = true;
      this.send = {
        id: row.id,
        carrier: "",
        trankNo: "",
        shipper: ""
      };
    },
    // 查看订单物流
    lookLogistics(e) {
      console.log(e, "查看订单物流");
      this.courierDialog = true;
      this.$refs.courier.init(e.id);
    },
    sendCancel() {
      this.sendVisible = false;
    },
    sendSubmit() {
      this.$https.postXform("order/orderSend", this.send).then(res => {
        this.$message({ message: "发货成功", type: "success" });
        this.sendVisible = false;
        this.getList();
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      if (formName == "queryParam") {
        this.getList();
        this.sourceIdVisable=false;
      }
    },
    allRefundDialog(row) {
      this.$confirm("是否同意退款申请?", "提示", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "拒绝",
        type: "warning"
      })
        .then(() => {
          this.$https
            .postXform("order/agreeAllRefund", { id: row.id })
            .then(res => {
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.getList();
            });
        })
        .catch(action => {
          if (action === "cancel") {
            this.$https
              .postXform("order/rejectAllRefund", { id: row.id })
              .then(res => {
                this.$message({
                  type: "success",
                  message: "拒绝成功!"
                });
                this.getList();
              });
          }
        });
    },
    exportExcel() {
      let date1 = null,
        date2 = null;
      if (
        this.queryParam.timespan != null &&
        this.queryParam.timespan.length > 1
      ) {
        date1 = this.queryParam.timespan[0];
        date2 = this.queryParam.timespan[1];
      }
      let param = {
        id: this.queryParam.id,
        orderNo: this.queryParam.orderNo,
        customerId: this.queryParam.customerId,
        status: this.queryParam.status,
        startDate: date1,
        endDate: date2,
        sourceType: this.queryParam.sourceType
      };
      var str = [];
      for (var p in param) {
        if (param[p] !== undefined && param[p] !== null) {
          //注：这里必须讲 false 排除在外，否则传入实际false将跳过处理。
          str.push(encodeURIComponent(p) + "=" + encodeURIComponent(param[p]));
        }
      }
      this.downExcelUrl =
        process.env.VUE_APP_ADMIN_BASE_URL + "order/export?" + str.join("&");
      console.log(this.downExcelUrl);
      this.$nextTick(function() {
        // DOM 更新了
        document.getElementById("downExcel").click();
      });
    },
    changeType(key) {
      this.sourceIdList = [];
      this.queryParam.sourceId = null;
      if (!key) {
        this.sourceIdVisable = false;
        return;
      }
      if (this.queryParam.sourceType == 1) {
        this.sourceIdRemoteUrl = "sendMessage/doctor";
        // sourceIdRemoteUrl= "医生宣传";
      } else if (this.queryParam.sourceType == 2) {
        this.sourceIdRemoteUrl = "sendMessage/distribute";
        // sourceIdRemoteUrl= "代理宣传";
      } else if (this.queryParam.sourceType == 3) {
        this.sourceIdRemoteUrl = "sendMessage/customer";
        // sourceIdRemoteUrl= "客户";
      } else if (this.queryParam.sourceType == 4) {
        this.sourceIdRemoteUrl = "sendMessage/store";
        // sourceIdRemoteUrl= "门店";
      } else if (this.queryParam.sourceType == 5) {
        this.sourceIdRemoteUrl = "sendMessage/checkActivity";
        // sourceIdRemoteUrl= "筛查活动";
      } else {
        this.sourceIdVisable = false;
        return;
      }
      this.sourceIdVisable = true;
      this.remoteMethod('');
    },
    remoteMethod(query) {
      this.loading = true;
      this.sourceIdList = [];
      this.$https.get(this.sourceIdRemoteUrl, { name: query }).then(res => {
        this.loading = false;
        this.sourceIdList = res.data.data;
      });
    },
    dialogOrderProperties() {
      this.orderPropertiesDialog=true;
      this.$refs.orderProperties.initProperties();
    }
  }
};
</script>

<style lang="scss" scoped>
@import "../../assets/css/order/order.scss";
</style>
